package top.tenebrous.yzl.im.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yazhang6
 */
@Configuration
public class IMWorkPoolConfig {

	@Value("${yzl.im.work-pool.core-pool-size:5}")
	private Integer workPoolCoreSize;

	@Value("${yzl.im.work-pool.max-pool-size:10}")
	private Integer workPoolMaxSize;

	@Value("${yzl.im.work-pool.queue-capacity:1000}")
	private Integer queueCapacity;

	@Bean("yzlImThreadPoolScheduler")
	public ThreadPoolTaskExecutor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(workPoolCoreSize);
		executor.setMaxPoolSize(workPoolMaxSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setKeepAliveSeconds(60);
		executor.setThreadNamePrefix("yzl:im:thread:");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		executor.setWaitForTasksToCompleteOnShutdown(true);
		executor.setAwaitTerminationSeconds(60);
		return executor;
	}

	@Bean("yzlImScheduledThreadPoolScheduler")
	public ScheduledExecutorService scheduledExecutor() {
		return new ScheduledThreadPoolExecutor(workPoolCoreSize, new ThreadPoolExecutor.CallerRunsPolicy());
	}
}

